//
//  LeftAlignedCollectionViewFlowLayout.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/2.
//

#import "LeftAlignedCollectionViewFlowLayout.h"

@implementation LeftAlignedCollectionViewFlowLayout

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    
    for (UICollectionViewLayoutAttributes *attribute in attributes) {
        if (attribute.representedElementCategory == UICollectionElementCategoryCell) {
            UICollectionViewLayoutAttributes *newFrame = [self layoutAttributesForItemAtIndexPath:attribute.indexPath];
            attribute.frame = newFrame.frame;
        }
    }
    
    return attributes;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    UIEdgeInsets sectionInset = [self evaluatedSectionInsetForItemAtIndex:indexPath.section];
    CGRect frame = currentItemAttributes.frame;
    
    if (indexPath.item == 0) {
        frame.origin.x = sectionInset.left;
        currentItemAttributes.frame = frame;
        return currentItemAttributes;
    }
    
    NSIndexPath *previousIndexPath = [NSIndexPath indexPathForItem:indexPath.item - 1 inSection:indexPath.section];
    CGRect previousFrame = [self layoutAttributesForItemAtIndexPath:previousIndexPath].frame;
    CGFloat previousFrameRightPoint = previousFrame.origin.x + previousFrame.size.width;
    CGRect stretchedCurrentFrame = CGRectMake(sectionInset.left, frame.origin.y, self.collectionView.frame.size.width - sectionInset.left - sectionInset.right, frame.size.height);
    
    BOOL isFirstItemInRow = !CGRectIntersectsRect(previousFrame, stretchedCurrentFrame);
    
    if (isFirstItemInRow) {
        frame.origin.x = sectionInset.left;
    } else {
        frame.origin.x = previousFrameRightPoint + self.minimumInteritemSpacing;
    }
    
    currentItemAttributes.frame = frame;
    return currentItemAttributes;
}

- (UIEdgeInsets)evaluatedSectionInsetForItemAtIndex:(NSInteger)index {
    if ([self.collectionView.delegate respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)]) {
        id<UICollectionViewDelegateFlowLayout> delegate = (id<UICollectionViewDelegateFlowLayout>)self.collectionView.delegate;
        return [delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:index];
    } else {
        return self.sectionInset;
    }
}

@end
